package com.chinaoct.siku.gzw.report;


import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Title: DbUtils
 * @Package com.hd.rcugrc.product.oa.wisdommeeting.xmlcreate.util
 * @Description: db文件工具类
 * @Author wangyu
 * @Date: 2022/5/18
 * @Version 1.0
 */
public class DBUtils {
    private static Connection connection = null;
    private static Statement statement = null;
    private static Logger logger = LoggerFactory.getLogger(DBUtils.class);

    public static final HashMap<String,String> tableNameMap = new HashMap<String,String>() {{
        put("R_DB_3031272048", "供应链金融");
        put("R_DB_3031272045", "信用证");
        put("R_DB_3031272043", "应收票据");
        put("R_DB_3031272051", "金融衍生业务附表");
        put("R_DB_3031272042", "应付票据");
        put("R_DB_3031272054", "应收账款");
        put("R_DB_3031272056", "客商信息");
        put("R_DB_3031272050", "PPP附表");
        put("R_DB_3031272055", "应付账款");
        put("R_DB_3031272039", "资金结算");
        put("R_DB_3031272052", "增值税发票");
        put("R_DB_3031272046", "保函");
        put("R_DB_3031272049", "财务公司附表");
        put("R_DB_3031272047", "金融投资业务");
        put("R_DB_3031272044", "担保");
        put("R_DB_3031272041", "应付债券");
        put("R_DB_3031272038", "银行账户");
        put("R_DB_3031272053", "合同");
        put("R_DB_3031272040", "银行贷款");
    }};

    /**
     * 开始事务
     *
     * @param cnn
     */
    public static void beginTransaction(Connection cnn) {
        if (cnn != null) {
            try {
                if (cnn.getAutoCommit()) {
                    cnn.setAutoCommit(false);
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * 提交事务
     *
     * @param cnn
     */
    public static void commitTransaction(Connection cnn) {
        if (cnn != null) {
            try {
                if (!cnn.getAutoCommit()) {
                    cnn.commit();
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * 回滚事务
     *
     * @param cnn
     */
    public static void rollBackTransaction(Connection cnn) {
        if (cnn != null) {
            try {
                if (!cnn.getAutoCommit()) {
                    cnn.rollback();
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * @describe: 设置连接
     * @params:
     * @Author: zc
     * @Date: 2022/03/20
     */
    public static void setConnection(String path) {
        try {
            //            声明驱动类型
            Class.forName("org.sqlite.JDBC");
            //            设置 sqlite文件路径，等同于mysql连接地址(jdbc:mysql://127.0.0.1:3306/test)
            String url = "jdbc:sqlite:" + path;
            //            获取连接
            //             connection = DriverManager.getConnection(url, username, password);
            connection = DriverManager.getConnection(url);
            //            声明
            statement = connection.createStatement();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            throw new RuntimeException("建立Sqlite连接失败");
        }

    }



    /**
     * 判断是否是linux系统,对//符号进行处理
     *
     * @return
     */
    public static String isLinux(String filePath) {
        String os = System.getProperty("os.name");
        if (os.contains("Windows")) {
            return filePath.replace("/", "\\");
        } else {
            return filePath.replace("\\", "/");
        }
    }

    /**
     * @describe: 创建表
     * @params: tableName: 要创建的表的名称 className：项目中Pojo的类名(需要注意的是该类名需要加上包名 如 com.xxx.xxx.xxx)
     * @Author: zc
     * @Date: 2022/03/20
     */
    public synchronized static void createTable(String tableName, List<Map<String, String>> fieldNames) throws SQLException {
        try {
            StringBuilder builder = new StringBuilder();
            builder.append("CREATE TABLE '");
            builder.append(tableName);
            builder.append("'(");
            builder.append(" 'DSP_GUID' VARCHAR (32) NOT NULL," +
                    "  'DSP_ROW_STATUS' CHAR (1) NOT NULL," +
                    "  'DSP_DATA_TYPE' CHAR (1) NOT NULL," +
                    "  'DSP_TIMESTAMP' DATETIME NOT NULL,");
            for (Map<String, String> fieldName : fieldNames) {
                //字段名称
                String indxId = "COL_" + fieldName.get("INDX_ID");
                builder.append("'" + indxId + "'");
                //字段类型
                String indxDataType = fieldName.get("INDX_DATA_TYPE");
                if (indxDataType.equals("字符串型C")) {
                    builder.append(" VARCHAR (");
                } else if (indxDataType.equals("长文本TEXT")) {
                    builder.append(" TEXT (");
                } else if (indxDataType.equals("逻辑型L")) {
                    builder.append(" TEXT ");
                } else if (indxDataType.equals("货币型Y") || indxDataType.equals("十进制DECIMAL")) {
                    builder.append(" DECIMAL (");
                } else if (indxDataType.equals("数值型N") || indxDataType.equals("整型I")) {
                    builder.append(" INTEGER (");
                } else if (indxDataType.equals("双精度型B")) {
                    builder.append(" DOUBLE (");
                } else if (indxDataType.equals("日期型D")) {
                    builder.append(" DATE ");
                }
                //字段大小
                String indxDataLen = fieldName.get("INDX_DATA_LEN");
                if (!StringUtils.isEmpty(indxDataLen) && !indxDataType.equals("逻辑型L") &&!indxDataType.equals("日期型D")) {
                    builder.append(indxDataLen + ") ");
                }
                //是否必填
                String isnull = fieldName.get("IS_NULL");
                if ("是".equals(isnull)) {
                    builder.append(",");
                } else {
                    builder.append("NOT NULL,");
                }
            }

            builder.append("PRIMARY KEY (\"DSP_GUID\")" +
                    ");");
            boolean success = statement.execute(builder.toString());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("建表失败，表名称：" + tableName);
        }
    }


    /**
     * 查询表
     *
     * @param sql
     * @return
     * @throws SQLException
     */
    public synchronized static List<Map<String, String>> select(String sql) throws SQLException {
        ResultSet resultSet = statement.executeQuery(sql);
        List<Map<String, String>> list = new ArrayList();

        ResultSetMetaData md = resultSet.getMetaData();

        int columnCount = md.getColumnCount(); //Map rowData;

        while (resultSet.next()) { //rowData = new HashMap(columnCount);

            Map<String, String> rowData = new HashMap();

            for (int i = 1; i <= columnCount; i++) {

                rowData.put(md.getColumnName(i), String.valueOf(resultSet.getObject(i)));

            }

            list.add(rowData);

        }
        return list;
    }

    /**
     * 删除表
     *
     * @param tableName
     * @throws SQLException
     */
    public synchronized static void dropTable(String tableName) throws SQLException {
        String sql = "DROP TABLE " + tableName + ";";
        statement.execute(sql);
    }

    /**
     * @describe: 表中插入数据
     * @params: tableName：表名 list:待插入的对象集合 需要注意的是插入的对象要跟表名对应
     * @Author: zc
     * @Date: 2022/03/20
     */
    public synchronized static <T> boolean insert(String tableName, List<String> list) throws SQLException {
        StringBuilder sql = new StringBuilder();
        sql.append("INSERT INTO ");
        sql.append(tableName);
        sql.append(" VALUES (");
        boolean execute = false;
        try {
            String collect = list.stream().map(x -> "'" + x + "'").collect(Collectors.joining(",")).replace("'null'", "null");
            sql.append(collect);
            sql.append(")");
            logger.warn("插入数据：{}", String.valueOf(sql));
            statement.execute(String.valueOf(sql));
            return true;
        } catch (Exception exception) {
            exception.printStackTrace();
            logger.warn("无DB数据插入跳过:{}", list.toString());
            return execute;
        }
    }

    /**
     * @describe: 关闭链接
     * @params:
     * @Author: zc
     * @Date: 2022/03/20
     */
    public static void endConnection() {
        try {

            connection.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void createTableAndInsertData(String tableName, List<Map<String, String>> fieldNames, String rootPath, String path, List<String> filePaths, String dsp_data_type) throws SQLException, IOException {
        StringBuilder builder = new StringBuilder();
        builder.append("CREATE TABLE '");
        builder.append(tableName);
        builder.append("'(");
        builder.append(" 'DSP_GUID' VARCHAR (32) NOT NULL," +
                "  'DSP_ROW_STATUS' CHAR (1) NOT NULL," +
                "  'DSP_DATA_TYPE' CHAR (1) NOT NULL," +
                "  'DSP_TIMESTAMP' DATETIME NOT NULL,");
        for (Map<String, String> fieldName : fieldNames) {
            //字段名称
            String indxId = "COL_" + fieldName.get("INDX_ID");
            builder.append("'" + indxId + "'");
            //字段类型
            String indxDataType = fieldName.get("INDX_DATA_TYPE");
            if (indxDataType.equals("字符串型C")) {
                builder.append(" VARCHAR (");
            } else if (indxDataType.equals("长文本TEXT")) {
                builder.append(" TEXT (");
            } else if (indxDataType.equals("逻辑型L")) {
                builder.append(" TEXT ");
            } else if (indxDataType.equals("货币型Y") || indxDataType.equals("十进制DECIMAL")) {
                builder.append(" DECIMAL (");
            } else if (indxDataType.equals("数值型N") || indxDataType.equals("整型I")) {
                builder.append(" INTEGER (");
            } else if (indxDataType.equals("双精度型B")) {
                builder.append(" DOUBLE (");
            } else if (indxDataType.equals("日期型D")) {
                builder.append(" DATE ");
            }else if (indxDataType.equals("日期时间型T")) {
                builder.append(" DATE ");
            }
            //字段大小
            String indxDataLen = fieldName.get("INDX_DATA_LEN");
            if (!StringUtils.isEmpty(indxDataLen) && !indxDataType.equals("逻辑型L") &&!indxDataType.equals("日期型D") &&!indxDataType.equals("日期时间型T")) {
                builder.append(indxDataLen + ") ");
            }
            //是否必填
            String isnull = fieldName.get("IS_NULL");
            if ("是".equals(isnull)) {
                builder.append(",");
            } else {
                builder.append("NOT NULL,");
            }
        }

        builder.append("PRIMARY KEY (\"DSP_GUID\")" +
                ");");
        try {
            boolean success = statement.execute(builder.toString()); //建表
        }catch (Exception e){
            logger.error(builder.toString());
            throw e;
        }

        List<Map<String,String>> maps = changeMap(tableName,path,filePaths);
        if(null!=maps && maps.size()>0){

            // 插入数据
            for(Map<String,String> map:maps){
                // 拼装insert语句
                StringBuilder insertStr = new StringBuilder();
                insertStr.append("INSERT INTO  '");
                insertStr.append(tableName);
                insertStr.append("'(");
                insertStr.append(" 'DSP_GUID','DSP_ROW_STATUS','DSP_DATA_TYPE','DSP_TIMESTAMP',");
                for (Map<String, String> fieldName : fieldNames) {
                    // 字段名称
                    String indexId = "COL_" + fieldName.get("INDX_ID");
                    insertStr.append("'" + indexId + "'");
                    insertStr.append(",");
                    // 去除最后的,
                }
                insertStr = insertStr.deleteCharAt(insertStr.length() - 1);
                String uuid = getUuid();
                Date date = new Date();
                Calendar calender = Calendar.getInstance();
                calender.setTime(date);
                String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calender.getTime());
                insertStr.append(")");
                insertStr.append(" values (");
                insertStr.append("'" + uuid + "'").append(",");
                insertStr.append(1).append(",");
                insertStr.append("'"+dsp_data_type+"'").append(",");
                insertStr.append("'" + nowTime + "'").append(",");

                for (Map<String, String> fieldName : fieldNames) {
                    String indxDataType = fieldName.get("INDX_DATA_TYPE");
                    String indexName = fieldName.get("INDX_NM"); // 指标
                    String indxId = fieldName.get("INDX_ID");
                    String indxDataLen = fieldName.get("INDX_DATA_LEN");
                    String indexValue = map.get(indexName);
                    //                        if(indexValue!=null){
                    //                            System.out.println("[关联模板id"+tableName+"]"+"[国资指标id："+indexId + "]  [国资委指标名称：" + indexName+"] [填报数据："+indexValue+"]");
                    //                        }
                    if (indxDataType.equals("货币型Y")) {
                        if (!StringUtils.isEmpty(indexValue)) {
                            insertStr.append(new BigDecimal(indexValue));
                        } else {
                            insertStr.append("NULL");
                        }
                    } else if (indxDataType.equals("数值型N")) {
                        if (!StringUtils.isEmpty(indexValue)) {
                            try {
                                insertStr.append(Integer.valueOf(indexValue));
                            }catch (Exception e){
                                insertStr.append(Double.valueOf(indexValue));
                            }
                        } else {
                            insertStr.append("NULL");
                        }
                    } else if (indxDataType.equals("双精度型B")) {
                        if (!StringUtils.isEmpty(indexValue)) {
                            insertStr.append(Double.valueOf(indexValue));
                        } else {
                            insertStr.append("NULL");
                        }
                    } else if(indxDataType.equals("日期型D")){
                        if (!StringUtils.isEmpty(indexValue)) {
                            if(StringUtils.isNotBlank(indxDataLen) && "10".equals(indxDataLen)){
                                if(indexValue.length()<10 && indexValue.length()>7){
                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                    try {
                                        Date d=sdf.parse(indexValue);
                                        indexValue=sdf.format(d);
                                    } catch (ParseException e) {

                                    }
                                }
                            }
                            insertStr.append("'" + indexValue + "'");
                        } else {
                            insertStr.append("''");
                        }
                    } else if(indxDataType.equals("十进制DECIMAL")){
                        if (!StringUtils.isEmpty(indexValue)) {
                            indexValue = indexValue.trim();
                            if(!isNumeric(indexValue)){
                                if(indexValue.indexOf(",")>0){
                                    indexValue=indexValue.replaceAll(",","");
                                } else {
                                    try{
                                        BigDecimal bd = new BigDecimal(indexValue);
                                        bd = bd.setScale(2, RoundingMode.HALF_UP); // 保留两位小数，HALF_UP是四舍五入
                                        double result = bd.doubleValue();
                                        indexValue= String.valueOf(result);
                                    }catch (Exception e){
                                        logger.error(indexValue+":"+e.getMessage());
                                        indexValue = "0.00";
                                    }
                                }
                            }
                            insertStr.append("'" + indexValue + "'");
                        } else {
                            insertStr.append("''");
                        }
                    }

                    else {
                        if(StringUtils.isNotBlank(indexValue)){
                            indexValue = indexValue.trim();
                            if(indexValue.indexOf("'")>=0){
                                indexValue = indexValue.replaceAll("'","''");
                            }
                        }
                        insertStr.append("'" + indexValue + "'");
                    }
                    // 全局map中获取数据
                    insertStr.append(",");
                }
                insertStr = insertStr.deleteCharAt(insertStr.length() - 1);
                // 去除最后的,
                insertStr.append(" );");
                try {
                    statement.execute(String.valueOf(insertStr));
                }catch (Exception e){
                    logger.error(insertStr.toString());
                    throw e;
                }
            }
            maps.clear();
        }
    }

    private static boolean isNumeric(String str) {
        return str.matches("-?\\d+(\\.\\d+)?");// 正则表达式 \d 是数字字符，+ 表示一次或多次。
    }

    private static String getUuid() {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
        boolean b  = true;
        while(b){
            if(uuid.matches("-?\\d+(\\.\\d+)?")){
                uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
            }else {
                b=false;
            }
        }
        return uuid;
    }

    private static List<Map<String, String>> changeMap(String tableName, String path, List<String> filePaths) throws IOException {
        List<Map<String,String>> list = new ArrayList<>();
        List<String[]> rows = new ArrayList<>();
        List<String> csvPaths= getPath(filePaths,path,tableName);
        if(null!=csvPaths && csvPaths.size()>0){
            int i=0;
            for(String csv:csvPaths){
                List<String[]> strings = CsvUtils.readerCsv(csv);
                if(null!=strings && strings.size()>0){
                    if(i>0){ //多表去除表头
                        strings.remove(0);
                    }
                    i++;
                    rows.addAll(strings);
                }

            }

        }
        if(rows.size()>1){
            String[] titles= rows.get(0);
            for(int i=1;i<rows.size();i++){
                String[] datas=rows.get(i);
                if(StringUtils.isEmpty(datas[0])){
                    continue;
                }
                Map<String,String> map =new HashMap<>();
                boolean hasValue=false;
                for (int j=0;j<titles.length;j++){
                    if(datas.length>j){
                        map.put(titles[j],datas[j]);
                        hasValue=true;
                    }else{
//                        logger.debug(titles[j]);
//                        logger.debug(String.valueOf(j));
                        map.put(titles[j],null);
                    }

                }
                if(hasValue){
                    list.add(map);
                }
            }
        }
        return list;

    }

    private static List<String> getPath(List<String> filePaths, String path, String tableName) {
        String name=tableNameMap.get(tableName);
        if(StringUtils.isBlank(name)){
            throw new RuntimeException("获取不到"+tableName+"的数据");
        }
        List<String> paths=new ArrayList<>();
        for(String s:filePaths){
            if(!s.endsWith("csv") || s.indexOf("_")<0){
                continue;
            }
            String[] names = s.split("_");
            if(names.length<6){
                continue;
            }
            if(name.equals(names[names.length-5])){
                paths.add(path+s);
            }
        }
        return paths;
    }

    public static void createTableAndInsertData2(String tableName, List<Map<String, String>> fieldNames, String rootPath, String path, List<String> filePaths, String dsp_data_type, String dataDate) throws SQLException, IOException {
        StringBuilder builder = new StringBuilder();
        builder.append("CREATE TABLE '");
        builder.append(tableName);
        builder.append("'(");
        builder.append(" 'DSP_GUID' VARCHAR (32) NOT NULL," +
                "  'DSP_ROW_STATUS' CHAR (1) NOT NULL," +
                "  'DSP_DATA_TYPE' CHAR (1) NOT NULL," +
                "  'DSP_TIMESTAMP' DATETIME NOT NULL,");
        for (Map<String, String> fieldName : fieldNames) {
            //字段名称
            String indxId = "COL_" + fieldName.get("INDX_ID");
            builder.append("'" + indxId + "'");
            //字段类型
            String indxDataType = fieldName.get("INDX_DATA_TYPE");
            if (indxDataType.equals("字符串型C")) {
                builder.append(" VARCHAR (");
            } else if (indxDataType.equals("长文本TEXT")) {
                builder.append(" TEXT (");
            } else if (indxDataType.equals("逻辑型L")) {
                builder.append(" TEXT ");
            } else if (indxDataType.equals("货币型Y") || indxDataType.equals("十进制DECIMAL")) {
                builder.append(" DECIMAL (");
            } else if (indxDataType.equals("数值型N") || indxDataType.equals("整型I")) {
                builder.append(" INTEGER (");
            } else if (indxDataType.equals("双精度型B")) {
                builder.append(" DOUBLE (");
            } else if (indxDataType.equals("日期型D")) {
                builder.append(" DATE ");
            }else if (indxDataType.equals("日期时间型T")) {
                builder.append(" DATE ");
            }
            //字段大小
            String indxDataLen = fieldName.get("INDX_DATA_LEN");
            if (!StringUtils.isEmpty(indxDataLen) && !indxDataType.equals("逻辑型L") &&!indxDataType.equals("日期型D") &&!indxDataType.equals("日期时间型T")) {
                builder.append(indxDataLen + ") ");
            }
            //是否必填
            String isnull = fieldName.get("IS_NULL");
            if ("是".equals(isnull)) {
                builder.append(",");
            } else {
                builder.append("NOT NULL,");
            }
        }

        builder.append("PRIMARY KEY (\"DSP_GUID\")" +
                ");");
        boolean success = statement.execute(builder.toString());

        List<Map<String,String>> maps = changeMap2(tableName,path,filePaths,rootPath,dataDate);
        if(null!=maps && maps.size()>0){
            for(Map<String,String> map:maps){
                // 拼装insert语句
                StringBuilder insertStr = new StringBuilder();
                insertStr.append("INSERT INTO  '");
                insertStr.append(tableName);
                insertStr.append("'(");
                insertStr.append(" 'DSP_GUID','DSP_ROW_STATUS','DSP_DATA_TYPE','DSP_TIMESTAMP',");
                for (Map<String, String> fieldName : fieldNames) {
                    // 字段名称
                    String indexId = "COL_" + fieldName.get("INDX_ID");
                    insertStr.append("'" + indexId + "'");
                    insertStr.append(",");
                    // 去除最后的,
                }
                insertStr = insertStr.deleteCharAt(insertStr.length() - 1);
                String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
                Date date = new Date();
                Calendar calender = Calendar.getInstance();
                calender.setTime(date);
                String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calender.getTime());
                insertStr.append(")");
                insertStr.append(" values (");
                insertStr.append("'" + uuid + "'").append(",");
                insertStr.append(1).append(",");
                insertStr.append("'"+dsp_data_type+"'").append(",");
                insertStr.append("'" + nowTime + "'").append(",");

                for (Map<String, String> fieldName : fieldNames) {
                    String indxDataType = fieldName.get("INDX_DATA_TYPE");
                    String indexName = fieldName.get("INDX_NM"); // 指标
                    String indexId = fieldName.get("INDX_ID");
                    String indexValue = map.get(indexName);
                    //                        if(indexValue!=null){
                    //                            System.out.println("[关联模板id"+tableName+"]"+"[国资指标id："+indexId + "]  [国资委指标名称：" + indexName+"] [填报数据："+indexValue+"]");
                    //                        }
                    if (indxDataType.equals("货币型Y")) {
                        if (!StringUtils.isEmpty(indexValue)) {
                            insertStr.append(new BigDecimal(indexValue));
                        } else {
                            insertStr.append("NULL");
                        }
                    } else if (indxDataType.equals("数值型N")) {
                        if (!StringUtils.isEmpty(indexValue)) {
                            try {
                                insertStr.append(Integer.valueOf(indexValue));
                            }catch (Exception e){
                                insertStr.append(Double.valueOf(indexValue));
                            }
                        } else {
                            insertStr.append("NULL");
                        }
                    } else if (indxDataType.equals("双精度型B")) {
                        if (!StringUtils.isEmpty(indexValue)) {
                            insertStr.append(Double.valueOf(indexValue));
                        } else {
                            insertStr.append("NULL");
                        }
                    } else {
                        insertStr.append("'" + indexValue + "'");
                    }
                    // 全局map中获取数据
                    insertStr.append(",");
                }
                insertStr = insertStr.deleteCharAt(insertStr.length() - 1);
                // 去除最后的,
                insertStr.append(" );");
                statement.execute(String.valueOf(insertStr));
            }
        }
    }

    private static List<Map<String, String>> changeMap2(String tableName, String path, List<String> filePaths, String rootPath, String dataDate) throws IOException {
        List<Map<String,String>> list = new ArrayList<>();
        String filePath = isLinux(rootPath + "\\非结构化数据\\附件");
        File destDir = new File(filePath);
        // 如果目标目录路径不存在，则创建
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        // 清空目录下文件
        File[] oldFiles = destDir.listFiles();
        if (oldFiles != null || oldFiles.length>0) {
            for(File f:oldFiles){
                if(f.equals(destDir)){
                    continue;
                }
                f.delete();
            }
        }
        // 复制文件到附件目录
        Map<String,List<File>> fileMap =new HashMap<>();
        for(String name : tableNameMap.values()){
            for(String s:filePaths){
                if(!s.endsWith("csv") || s.indexOf("_")<0){
                    continue;
                }
                String[] names = s.split("_");
                if(names.length<6){
                    continue;
                }
                if(name.equals(names[names.length-5])){
                    File file = new File(path+s);
                    // 目标文件路径
                    File destFile = new File(destDir, file.getName());
                    FileUtils.copyFile(file,destFile);
                    if(fileMap.containsKey(name)){
                        fileMap.get(name).add(destFile);
                    }else {
                        List<File> list1 = new ArrayList<>();
                        list1.add(destFile);
                        fileMap.put(name,list1);
                    }

                }
            }
        }

        for(String key:fileMap.keySet()){
            Map<String,String> map =new HashMap<>();
            map.put("附件对应的信息资源名称",key);
            map.put("数据日期",dataDate);
            map.put("备注","");
            StringBuffer attachmentNames = new StringBuffer();
            for (File file : fileMap.get(key)) {
                attachmentNames.append(removeFileName(file.getPath())).append(",");
            }

            if (attachmentNames.length() > 0) {
                // 删除最后的字符
                attachmentNames = attachmentNames.deleteCharAt(attachmentNames.length() - 1);
            }
            map.put("附件",attachmentNames.toString());
            list.add(map);
        }
        boolean hasCheckFile = false;
        for(String s:filePaths){
            if(s.indexOf("中央企业司库信息系统数据核验表")>0){
                File file = new File(path+s);
                File destFile = new File(destDir, file.getName());
                FileUtils.copyFile(file,destFile);
                String fileName=removeFileName(destFile.getPath());
                Map<String,String> map =new HashMap<>();
                map.put("附件对应的信息资源名称","中央企业司库信息系统数据核验表");
                map.put("数据日期",dataDate);
                map.put("备注","");
                map.put("附件",fileName);
                list.add(map);
                hasCheckFile = true;
            }
        }
//        if(!hasCheckFile){
//            throw new RuntimeException("没有对应的【中央企业司库信息系统数据核验表】");
//        }
        return  list;
    }

    /**
     * 根据md5编码的方式识别文件内容后对文件名称进行修改
     *
     * @param path
     * @return
     */
    public static String removeFileName(String path) {
        try {
            // String path = isLinux(rootPath+"\\非结构化数据\\附件\\"+fileName);
            File file = new File(path);
            FileInputStream inputStream = new FileInputStream(path);
            String md5Digest = DigestUtils.md5Hex(inputStream).toUpperCase();
            String name = isLinux(file.getParent() + "\\" + md5Digest + "_" + file.getName());
            inputStream.close();
            File file1 = new File(name);
            file.renameTo(file1);
            return file1.getName();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("修改文件名出错出错了:" + path);
            return null;
        }
    }
}

